<template>
  <div :class="['bubble',show?'':'hide']" ref="listDom">
    <ul class="comments-list">
      <transition-group name="bottomUp">
        <BubbleCommentItem v-for="(comment,index) in playComments" :key="comment.commentId" :comment="comment"
                           class="comments-item"/>
      </transition-group>
    </ul>
  </div>
</template>

<script setup>
import {defineProps, onMounted, onUnmounted, ref, toRefs, watch, defineEmits} from "vue";
import BubbleCommentItem from "./item/BubbleCommentItem.vue";

let propsDef = defineProps({
  comments: {
    type: Array,
    default: []
  },
  hotComments: {
    type: Array,
    default: []
  },
  maxCount: {
    type: Number,
    default: 10
  },
  mid: {
    type: Number
  },
  show: {
    type: Boolean,
    default: false
  }
});
let emit = defineEmits(["getData"]);
let props = toRefs(propsDef);
let playComments = ref([]);
let commentsIndex = ref(0);
let listDom = ref(null);

watch(props.mid, () => {
  playComments.value = [];
  commentsIndex.value = 0;
});

function addNext() {
  if (!propsDef.show) {
    return;
  }
  let allComment = [...propsDef.hotComments, ...propsDef.comments];
  let comment = allComment[commentsIndex.value];
  if (comment) {
    playComments.value.push(comment);
  }
  if (commentsIndex.value < allComment.length) {
    commentsIndex.value++;
  }
  if (commentsIndex.value > propsDef.maxCount) {
    hideComment();
  }
  if(commentsIndex > propsDef.maxCount - 3){
    emit("getData");
  }
}

let timer = null;
let timer1 = null;
onMounted(() => {
  listen();
});

function listen(){
  timer1 = setInterval(() => {
    let dom = listDom.value;
    if (dom) {
      dom.scrollTop = dom.scrollHeight;
    }
  }, 500);
  timer = setInterval(() => {
    if (propsDef.show) {
      addNext();
    }
  }, 2000)
}

onUnmounted(() => {
  clearInterval(timer);
  clearInterval(timer1);
});


function hideComment() {
  playComments.value.shift();
}


</script>

<style lang="scss" scoped>
.bottomUp-enter-active {
  display: none;
}


.bubble {
  position: fixed;
  display: flex;
  align-items: flex-end;
  flex-wrap: wrap;
  z-index: 2004;
  width: 100%;
  height: 16rem;
  overflow: scroll;

  &.hide {
    transform: scale(0);
  }

  .comments-list {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
  }
}
</style>